;; Non-robust matrix functions
;; Copyright (C) 2021  Rocks Mazama
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

(ns mazama.linalg.matrix.print
  (:require
   [mazama.linalg.matrix :as matrix]))

(defn- format-value
  [width x]
  (format (str "%" width "s") x))

(defn- matrix-column-widths
  [{:keys [ncols data]}]
  (->> data
       (map (comp inc count str))
       (matrix/columns ncols)
       (map #(reduce max %))))

(defn- print-matrix-row-fn
  [m]
  (let [widths (matrix-column-widths m)]
    (fn [row]
      (apply println (map format-value widths row)))))

(defn print-matrix
  "Print the matrix `m`."
  [m]
  (let [f (print-matrix-row-fn m)]
    (doseq [x (matrix/rows m)]
      (f x))))
